﻿/********************************************************************************
** 作者： 易景安
** 创建时间： 2011-11-15
** 描述：
** 用户管理-涉及到的相关方法
********************************************************************************/

var storeUser;     // 用户数据源
var gridUser;      // 用户Grid
var pageSize = 20; // 每页显示数
var winAddUser;    // 打开用户窗体
var winEditUser;   // 打开用户窗体
var UserID;
var UserActionForm; var UserActionWindow;

Ext.onReady(function() {
    Ext.QuickTips.init();
    // 本地加载图片代码
    Ext.BLANK_IMAGE_URL = strPath + 'extjs/resources/images/default/s.gif';

    // 选择监测点列表
    var httpProxy = new Ext.data.HttpProxy({
        url: strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=GetFoothillUserByPage'
    });
    // 监测点的读取方式
    var readerProxy = new Ext.data.JsonReader({
        root: 'Records',
        totalProperty: 'totalCount',
        fields: [
                  { name: 'UserID' },
                  { name: 'UserName' },
                  { name: 'TrueName' },
                  { name: 'Sex' },
                  { name: 'Status' },
                  { name: 'MobilePhone' },
                  { name: 'Email' },
                  { name: 'Remark' },
                  { name: 'RoleName' },
                  { name: 'Position' },
                  { name: 'OrganLabel' },
                  { name: 'OrderID' },
                  { name: 'OrganName' }
             ]
    });
    // 定义监测点数据源
    storeUser = new Ext.data.Store({
        proxy: httpProxy,
        reader: readerProxy,
        remoteSort: true
    });
    // 设置显示列的Title
    var ChooseView = new Ext.grid.GridView({ forceFit: true, sortAscText: '升序', sortDescText: '降序' });
    ChooseView.columnsText = '列显示/隐藏';
    // 加载前的事件
    storeUser.on('beforeload', function() {
        var UserName = Ext.get("txtUserName").dom.value;
        var Status = Ext.get("chStatus").dom.checked;
        var Forbid = Ext.get("chStatusNo").dom.checked;
        if (Status && Forbid) Status = 2;
        else if (Status && !Forbid) Status = 1;
        else if (!Status && Forbid) Status = 0;
        else Status = "3";
        var TrueName = Ext.get("txtTrueName").dom.value;
        storeUser.baseParams = {
            UserName: UserName, TrueName: TrueName, Status: Status
        };
    });
    // 设置页脚的显示样式。
    var ChooseBar = new Ext.PagingToolbar({
        pageSize: pageSize,
        store: storeUser,
        beforePageText: '第',
        afterPageText: '页 共{0}页',
        firstText: '第一页',
        prevText: '前一页',
        nextText: '后一页',
        lastText: '最后一页',
        refreshText: '刷新',
        displayInfo: true,
        displayMsg: '显示第 {0} - {1} 条数据, 共 {2} 条数据',
        emptyMsg: "没有数据可以显示"
    });
    // grid的选择列
    var smUserListModel = new Ext.grid.CheckboxSelectionModel({
        singleSelect: false,
        listeners: {
            rowselect: function(sm, row, rec) {
            }
        }
    });

    var GridToolBar = new Ext.Panel({
        labelAlign: 'top',
        frame: false,
        bodyStyle: 'border:0px;',
        width: "100%",
        html: '<table width="100%" border="0" cellspacing="0" cellpadding="0" style="background:#BFEAFD;"><tr><td width="70px" align="right" height="26">&nbsp;登录账号：</td><td align="left" style="width:420px;"><table border="0" cellspacing="0" cellpadding="0"><tr><td width="80px" align="left"><input type="text" id="txtUserName"  style="width:90px;" onkeydown="if(event.keyCode==13){doSearchUser(true);return false;}"/></td><td width="70px" align="right">用户姓名：</td><td align="left"><input type="text" id="txtTrueName" style="width:90px;" onkeydown="if(event.keyCode==13){doSearchUser(true);return false;}" /></td><td width="50px" align="right">状态：</td><td><input name="chStatus" type="checkbox" value="1" checked="true" />启用<input name="chStatusNo" type="checkbox" value="0" checked="true" />禁用</td></tr></table></td><td align="left"><input name="button" type="button" style="padding: 0px 5px; height: 22px;" id="btnSearchAll" onclick="doSearchUser(true);" value="查 询" /></td></tr><tr id="RoleManage"><td height="26" colspan="5" align="left"><table border="0" cellspacing="0" cellpadding="0"><tr><td width="28" height="20" align="center" id="divAddRoleInfoImg"><img src="images/ico_28.gif" width="16" height="16" /></td><td width="40" class="general_h1_gray_c01_font" id="divAddRoleInfo"><span style="cursor: hand;text-decoration:underline;" onclick="ShowUserWin();">新增</span></td><td width="24" align="center" class="general_h1_gray_c01_font" id="divAllotImg"><img src="images/ico_23.gif" width="16" height="16" /></td><td width="65" align="left" class="general_h1_gray_c01_font" id="divAccept"><span style="cursor: hand; text-decoration: underline;" onclick="ShowSetUserPassWin();">修改密码</span></td><td width="40" align="left" class="general_h1_gray_c01_font" id="divAllot"><span style="cursor: hand; text-decoration: underline;" onclick="SetStartStatus();">启用</span></td><td width="24" align="center" class="general_h1_gray_c01_font" id="divFeedbackImg"><img src="images/ico_25.gif" width="16" height="16" /></td><td width="40" align="left" class="general_h1_gray_c01_font" id="divFeedback"><span style="cursor: hand; text-decoration: underline;" onclick="SetStopStatus();">禁用</span></td><td width="28" align="center" class="general_h1_gray_c01_font" id="divCancellationImg"><img src="images/ico_21.gif" width="16" height="16" /></td><td width="40" align="left" class="general_h1_gray_c01_font" id="divCancellation"><span style="cursor: hand;text-decoration:underline;" onclick="DelUser();">删除</span></td></tr></table></td></tr></table>'
    });
    // 用户Grid的定义
    gridUser = new Ext.grid.GridPanel({
        id: 'pagedef-grid',
        store: storeUser,
        renderTo: "divUserInfo",
        cm: new Ext.grid.ColumnModel([
            smUserListModel,
            { id: 'UserID', header: "用户ID", sortable: false, dataIndex: 'UserID', hidden: true }, // ,renderer:renderOpenUserInfo
            {header: "登录账号", sortable: true, dataIndex: 'UserName' },
            { header: "用户姓名", sortable: true, dataIndex: 'TrueName', renderer: OpenUserInfo },
            { header: "所在部门", sortable: false, dataIndex: 'OrganName' },
            { header: "性别", sortable: true, dataIndex: 'Sex', renderer: SetSex },
            { header: "手机", sortable: true, dataIndex: 'MobilePhone' },
            { header: "邮箱", sortable: true, dataIndex: 'Email' },
            { header: "状态", sortable: true, dataIndex: 'Status', renderer: SetStatus },
            { header: "用户角色分配", sortable: true, dataIndex: 'UserID', renderer: OpenSetUserRole },
            { header: "用户权限分配", sortable: true, dataIndex: 'UserID', renderer: OpenSetUserAction }
        ]),
        sm: smUserListModel,
        height: parent.Ext.get("ContentFrame").getHeight() - 25,
        bbar: ChooseBar,
        view: ChooseView,
        frame: false,
        border: false,
        tbar: GridToolBar
    });

    gridUser.addListener('rowdblclick', function(gridObj, rowIdx, e) {
        // GetChoosePoint();
    });

    // 查看用户
    function OpenUserInfo(value, metadate, record, colIndex, rowIndex) {
        return "<a href=\"javascript:GetUserInfo('" + record.get("UserID") + "')\" title='" + value + "'>" + value + "</a>";
    }
    // 设置用户角色
    function OpenSetUserRole(value, metadate, record, colIndex, rowIndex) {
        return "<a href=\"javascript:OpenUserRoleWin('" + record.get("UserID") + "')\" title='用户角色分配'>分配角色</a>";
        // return "<a href=\"javascript:SetUserRole('"+record.get("UserID")+"')\" title='用户角色分配'>分配角色</a>";
    }
    // 设置用户权限
    function OpenSetUserAction(value, metadate, record, colIndex, rowIndex) {
        return "<a href=\"javascript:OpenResourceWin('" + record.get("UserID") + "')\" title='用户权限分配'>分配权限</a>";
        // return "<a href=\"javascript:SetUserAction('"+record.get("UserID")+"')\" title='用户权限分配'>分配权限</a>";
    }
    // 设置用户性别
    function SetSex(value, metadate, record, colIndex, rowIndex) {
        if (value == '1') return "男";
        else if (value == '0') return "女";
        else return "男";
    }
    // 设置用户状态
    function SetStatus(value, metadate, record, colIndex, rowIndex) {
        if (value == 1) return "启用";
        else return "禁用";
    }
    // 用户查询
    doSearchUser(true);
});

// 设置用户角色
function SetUserRole(UserID) {
    //创建一个HttpProxy
    var fromRoHttpProxy = new Ext.data.HttpProxy({
        url: strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=SearchNotUserRole&UserID=' + UserID
    });

    //创建一个JsonReader
    var fromRoRecord = new Ext.data.JsonReader({
        root: 'data',
        fields: [
                      { name: 'RoleID' },               //角色编码
                      {name: 'RoleName'}              //角色名称
                   ]
    });
    // 定义选择角色数据源
    var fromRoStore = new Ext.data.Store({
        proxy: fromRoHttpProxy,
        reader: fromRoRecord,
        remoteSort: true
    });
    //创建一个HttpProxy,已选择角色
    var toRoHttpProxy = new Ext.data.HttpProxy({
        url: strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=SearchUserRole&UserID=' + UserID
    });
    //创建一个JsonReader，已选择角色
    var toRoRecord = new Ext.data.JsonReader({
        root: 'data',
        fields: [
                      { name: 'RoleID' },               //角色编码
                      {name: 'RoleName'}              //角色名称
                   ]
    });
    // 定义已选择人员数据源
    var toRoStore = new Ext.data.Store({
        proxy: toRoHttpProxy,
        reader: toRoRecord,
        remoteSort: true
    });
    //定义一个Form,角色用户分配
    UserRoleForm = new Ext.form.FormPanel({
        width: 480,
        border: false,
        layout: 'fit',
        bodyStyle: 'padding:10px;',
        items: [{
            xtype: "itemselector",
            name: "itemselector",
            dataFields: ["RoleID", "RoleName"],
            valueField: "RoleID",
            displayField: "RoleName",
            imagePath: strPath + "extjs/multiselect/images/",
            toLegend: "已分配角色",
            fromLegend: "可分配角色",
            toStore: toRoStore,
            fromStore: fromRoStore
        }
        ],
        buttons: [{
            text: '确定',
            handler: function() {
                if (UserRoleForm.getForm().isValid()) {
                    UpdateUserRole(UserID);
                }
            }
        },
        {
            text: '关闭',
            handler: function() {
                if (UserRoleForm.getForm().isValid()) {
                    UserRoleWindow.hide();
                }
            }
        }
        ]
    });

    //定义一个窗体,角色用户分配
    UserRoleWindow = new Ext.Window({
        title: '用户角色分配',
        width: 480,
        height: 400,
        layout: 'fit',
        plain: true,
        bodyStyle: 'padding:10px;',
        buttonAlign: 'center',
        items: UserRoleForm
    });
    UserRoleWindow.show();
    fromRoStore.load();
    toRoStore.load();
}

// 设置用户角色
function UpdateOrganRole(UserID, RoleIDs) {
    // 获取选中的ID
    var strUrl = strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=SetUserRoles';
    Ext.Ajax.request({
        url: strUrl,
        method: 'POST',
        params: {
            UserID: UserID,
            RoleIDs: RoleIDs
        },
        failure: function(response, options) {
            ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
        },
        success: function(response, options) {
            var json = response.responseText;
            var obj = parseJsonResult(json);

            if (!obj.Success) {
                showMessage("错误！", "设置用户状态出现错误！请查看详细原因。", obj.Message);
            }
        }
    });
}

// 设置用户功能
function SetUserAction(UserID) {
    //创建一个HttpProxy
    var fromHttpProxy = new Ext.data.HttpProxy({
        url: strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=SearchNotUserAction&UserID=' + UserID
    });

    //创建一个JsonReader
    var fromRecord = new Ext.data.JsonReader({
        root: 'data',
        fields: [
                      { name: 'ActionID' },               //人员编码
                      {name: 'ActionName'}              //人员名称
                   ]
    });
    // 定义选择人员数据源
    var fromStore = new Ext.data.Store({
        proxy: fromHttpProxy,
        reader: fromRecord,
        remoteSort: true
    });
    //创建一个HttpProxy,已选择人员
    var toHttpProxy = new Ext.data.HttpProxy({
        url: strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=SearchUserAction&UserID=' + UserID
    });
    //创建一个JsonReader，已选择人员
    var toRecord = new Ext.data.JsonReader({
        root: 'data',
        fields: [
                      { name: 'ActionID' },               //人员编码
                      {name: 'ActionName'}              //人员名称
                   ]
    });
    // 定义已选择人员数据源
    var toStore = new Ext.data.Store({
        proxy: toHttpProxy,
        reader: toRecord,
        remoteSort: true
    });
    //定义一个Form,角色用户分配
    UserActionForm = new Ext.form.FormPanel({
        width: 480,
        border: false,
        layout: 'fit',
        bodyStyle: 'padding:10px;',
        items: [{
            xtype: "itemselector",
            name: "itemselector",
            dataFields: ["ActionID", "ActionName"],
            valueField: "ActionID",
            displayField: "ActionName",
            imagePath: strPath + "extjs/multiselect/images/",
            toLegend: "已分配权限",
            fromLegend: "可分配权限",
            toStore: toStore,
            fromStore: fromStore
        }
        ],
        buttons: [{
            text: '确定',
            handler: function() {
                if (UserActionForm.getForm().isValid()) {
                    UpdateUserAction(UserID);
                }
            }
        },
            {
                text: '关闭',
                handler: function() {
                    if (UserActionForm.getForm().isValid()) {
                        UserActionWindow.hide();
                    }
                }
            }
        ]
    });

    //定义一个窗体,角色用户分配
    UserActionWindow = new Ext.Window({
        title: '用户权限分配',
        width: 480,
        height: 400,
        layout: 'fit',
        plain: true,
        bodyStyle: 'padding:10px;',
        buttonAlign: 'center',
        items: UserActionForm
    });
    UserActionWindow.show();
    fromStore.load();
    toStore.load();
}

// 设置用户功能
function UpdateUserAction(UserID, MenuID) {
    // 获取选中的ID
    // var ActionIDs = UserActionForm.getForm().getValues().itemselector;
    var strUrl = strPath + 'GGFW/BaseInfo/FoothillMenuCommand.fwf?Method=SetMenuUser';
    Ext.Ajax.request({
        url: strUrl,
        method: 'POST',
        params: {
            UserID: UserID,
            MenuIDs: MenuID
        },
        failure: function(response, options) {
            ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
        },
        success: function(response, options) {
            var json = response.responseText;
            var obj = parseJsonResult(json);

            if (!obj.Success) {
                showMessage("错误！", "设置用户状态出现错误！请查看详细原因。", obj.Message);
            }
        }
    });
}

// 打开选择权限的窗体
function OpenUserRoleWin(UserID) {
    // 提交
    var strUrl = strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=SearchUserRole';
    Ext.Ajax.request({
        url: strUrl,
        method: 'POST',
        params: {
            UserID: UserID
        },
        failure: function(response, options) {
            ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
        },
        success: function(response, options) {
            var json = response.responseText;
            var obj = parseJsonResult(json);

            if (obj == null || !obj.Success) {
                showMessage("错误！", "保存出现错误！请查看详细原因。", obj.Message);
            }
            else {
                var ids = "";
                for (var i = 0, len = obj.data.length; i < len; i++) {
                    if (i == 0)
                        ids = obj.data[i].RoleID + ',';
                    else
                        ids = ids + "," + obj.data[i].RoleID;
                }
                ShowRoleWin(ids, UserID, '用户角色分配');
            }
        }
    });
}

// 打开选择权限的窗体
function OpenResourceWin(UserID) {
    // 提交
    var strUrl = strPath + 'GGFW/BaseInfo/FoothillMenuCommand.fwf?Method=GetFunctionsByUser';
    Ext.Ajax.request({
        url: strUrl,
        method: 'POST',
        params: {
            UserID: UserID
        },
        failure: function(response, options) {
            ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
        },
        success: function(response, options) {
            var json = response.responseText;
            var obj = parseJsonResult(json);

            if (obj == null || !obj.Success) {
                showMessage("错误！", "保存出现错误！请查看详细原因。", obj.Message);
            }
            else {
                var ids = "";
                for (var i = 0, len = obj.data.length; i < len; i++) {
                    if (i == 0)
                        ids = obj.data[i].MenuID;
                    else
                        ids = ids + "," + obj.data[i].MenuID;
                }
                ShowUserMenuWin(ids, UserID, '用户权限分配');
            }
        }
    });
}

// 禁用用户
function SetStopStatus() {
    SetStatus(0);
}

// 启用用户
function SetStartStatus() {
    SetStatus(1);
}

// 删除用户 #开始 ---------------------------------------------------------------------------------------------------------------------------
function DelUser() {
    var strID = getSelectID(gridUser, 'UserID');
    if (strID == '' || strID == null) {
        Ext.MessageBox.alert("提示", "请选择数据！"); return;
    }
    Ext.MessageBox.confirm("询问", '确认要删除选中的用户吗？删除后将不可恢复！', function(btn) {
        if (btn == "yes") {
            var strUrl = strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=DeleteFoothillUser';
            Ext.Ajax.request({
                url: strUrl,
                method: 'POST',
                params: {
                    UserIDs: strID
                },
                failure: function(response, options) {
                    ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
                },
                success: function(response, options) {
                    var json = response.responseText;
                    var obj = parseJsonResult(json);

                    if (!obj.Success) {
                        showMessage("错误！", "删除用户出现错误！请查看详细原因。", obj.Message);
                    }
                    else {
                        doSearchUser(false);
                    }
                }
            });
        }
    });
}

// 设置用户状态 #开始 ---------------------------------------------------------------------------------------------------------------------------
function SetStatus(Status) {
    var strID = getSelectID(gridUser, 'UserID');
    if (strID == '' || strID == null) {
        Ext.MessageBox.alert("提示", "请选择数据！"); return;
    }
    Ext.MessageBox.confirm("询问", '确认要设置选中用户的状态吗？', function(btn) {
        if (btn == "yes") {
            var strUrl = strPath + 'GGFW/BaseInfo/FoothillUserCmd.fwf?Method=SetFoothillUserStatus&UserIDs=' + strID;
            Ext.Ajax.request({
                url: strUrl,
                method: 'POST',
                params: {
                    Status: Status
                },
                failure: function(response, options) {
                    ReturnValue = Ext.MessageBox.alert("警告", "网络异常或登录过期，请重新登录！");
                },
                success: function(response, options) {
                    var json = response.responseText;
                    var obj = parseJsonResult(json);

                    if (!obj.Success) {
                        showMessage("错误！", "设置用户状态出现错误！请查看详细原因。", obj.Message);
                    }
                    else {
                        doSearchUser(false);
                    }
                }
            });
        }
    });
}

// 设置用户密码
function ShowSetUserPassWin() {
    var row = gridUser.getSelections();
    if (row.length > 1) {
        Ext.MessageBox.alert("提示", "只能单个修改用户的密码！"); return;
    }
    var strID = getSelectID(gridUser, 'UserID');
    if (strID == '' || strID == null) {
        Ext.MessageBox.alert("提示", "请选择数据！"); return;
    }
    OpenWindow('UserDetail.aspx?UserID=' + strID + '&isEdit=' + true + '&isPassWord=' + true, '_top', 620, 170, 'modal', false);
}

// 编辑用户信息
function GetUserInfo(UserID) {
    OpenWindow('UserDetail.aspx?UserID=' + UserID + '&isEdit=' + true, '_top', 620, 290, 'modal', false);
}

// 显示用户窗体
function ShowUserWin() {
    UserID = '';
    OpenWindow('UserDetail.aspx?UserID=' + UserID + '&isEdit=' + false, '_top', 620, 320, 'modal', false);
}

// 重新加载用户
function doSearchUser(isFirstPage) {
    var UserName = Ext.get("txtUserName").dom.value;
    var TrueName = Ext.get("txtTrueName").dom.value;
    var Status = Ext.get("chStatus").dom.checked;
    var Forbid = Ext.get("chStatusNo").dom.checked;
    if (Status && Forbid) Status = 2;
    else if (Status && !Forbid) Status = 1;
    else if (!Status && Forbid) Status = 0;
    else Status = 3;
    if (storeUser == null) return;
    if (isFirstPage) storeUser.load({ params: { start: 0, limit: pageSize, UserName: UserName, TrueName: TrueName, Status: Status} });
    else storeUser.load({ params: { start: (gridUser.getBottomToolbar().getPageData().activePage - 1) * pageSize, limit: pageSize, UserName: UserName, TrueName: TrueName, Status: Status} });
}

// 打开模式窗体的方法。
function OpenWindow(url, target, w, h, mode, refurbish) {
    var hWin = true;
    if (mode == 'modal') {
        hWin = window.showModalDialog(url, target, 'status:no;scrollbars;no;help:no;resizable:no;menubar=no;toolbar=no;location=no;dialogwidth:' + w + 'px;dialogheight:' + h + 'px');
        doSearchUser(false);
    }
    else {
        hWin = window.open(url, target, 'width=' + w + 'px,height=' + h +
                                        'px,left=' + (screen.width - w) / 2 + 'px,top=' + (screen.height - h) / 2 +
                                        'px,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no,alwaysRaised=yes');
    }
    if (refurbish) this.location = this.location;  // 刷新父窗体
}